<?php
namespace app\common\service;

use app\common\model\ProductCat as ProductCatModel;

class ProductCat{

    public function find($id){

        $productCatModel = new ProductCatModel();
        $productCat = $productCatModel -> find($id);

        return $productCat;
    }

    /**
     * 获取被整理好的树
     */
    public function getMenusTree(){

        $menus = ProductCatModel::all();
        $menus = collection($menus)->toArray();
        $menusById = [];
        foreach($menus as $val){
            $menusById[$val['id']] = $val;
        }
        $tree = $this->findSub($menusById,0);
        return $tree;
    }

    /**
     * 生成无限级的树 应用上只要三级
     * @param $menus
     * @param $pid
     * @return array
     */
    private function findSub($menus,$pid){
        $tree = [];
        foreach($menus as $val){
            if($val['pid'] == $pid){
                $tmpVal = $val;
                $tmpPid = $val['id'];
                unset($val);
                $tmpVal['sub'] = $this->findSub($menus,$tmpPid);
                array_push($tree,$tmpVal);
            }
        }
        return $tree;
    }

    /**
     * 找到一个分类的所有的下级
     * 如果分类超多 这些方法都不能用了
     */
    public function findAllSubCat($catId){
        $all = ProductCatModel::all();
        $all = collection($all)->toArray();

        $sub = $this->collectSub($all,[$catId]);
        return $sub;
    }

    private function collectSub($catsById,$pid=[0]){

        $returnSubCats= [];
        foreach($catsById as $key => $val){
            if(in_array($val['pid'],$pid)){
                array_push($returnSubCats,$val['id']);
                unset($catsById[$key]);
            }
        }
        if(empty($returnSubCats)) return [];
        $subReturnSubCats = $this->collectSub($catsById,$returnSubCats);
        $return = array_merge($returnSubCats,$subReturnSubCats);
        return $return;
    }


    public function insert($data){
        $productCatModel = new ProductCatModel();

        $result = $productCatModel->validate('ProductCatValidate.add')->save($data);

        if(false === $result){
            return ['state'=>0,'message'=>$productCatModel->getError()];
        }

        return ['state'=>1,'message'=>'','insertId'=>$productCatModel->id];
    }

    public function update($data){

        $productCatModel = new ProductCatModel();

        if(intval($data['id']) <1){
            return ['state'=>0,'message'=>"参数错误"];
        }

        $result = $productCatModel->validate('ProductCatValidate.edit')->save($data,['id'=>intval($data['id'])]);

        if(false === $result){
            return ['state'=>0,'message'=>$productCatModel->getError()];
        }

        return ['state'=>1,'message'=>''];
    }

    public function delete($ids){
        $productCatModel = new ProductCatModel();

        $count = $productCatModel ->destroy($ids);

        return $count;
    }
}